Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

If

If examples

Here are the basic examples of IF statement. This includes very basic examples to understand the concept and working of If condition in java.

Example 1: Checking if a Number is Positive:

Positive or not example in java
public class Main{ public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("This number is positive."); } } }

Output

This number is positive.
In this example, the number 10 is greater than zero. so it passed the condition and the output is "This number is positive."

Example 2: Checking Even or Odd:

Even or Odd example in java
public class Main{ public static void main(String[] args) { int num = 7; if (num % 2 == 0) { System.out.println("This number is even."); } else { System.out.println("This number is odd."); } } }

Output

This number is odd.
In this example, the modulus of 7 is 1. so the first condition failed and the else condition is executed as "This number is odd."

Example 3: Determining Eligibility for Voting:

Vote eligibility check in java
public class Main{ public static void main(String[] args) { int age = 19; if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote."); } } }

Output

You are eligible to vote.
In this example, the age is 19. so the first if condition passed and gave the output as "You are eligible to vote." and it did not executed the else as the if condition already passed

Example 4: Checking Pass or Fail:

Pass or Fail example in java
public class Main{ public static void main(String[] args) { int marks = 75; if (marks >= 50) { System.out.println("Congratulations! You are passed."); } else { System.out.println("Sorry, you didn't passed."); } } }

Output

Congratulations! You are passed.
In this example, the marks obtained is 75. so the first if condition checked for marks greater than 50 and it is executed, the output is "Congratulations! You are passed."

Example 5: Handling User Input:

Example with user input in java
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); int userAge = scanner.nextInt(); if (userAge >= 18) { System.out.println("You are eligible to vote"); } else { System.out.println("You are not eligible."); } scanner.close(); } }

Output

Enter your age:20 You are eligible to vote
In this last example, the program uses the Scanner class to take user input and then uses the if statement to determine whether the user is eligible to vote or not based on their entered age.

  📌TAGS

★If ★condition ★java ★java if ★if else ★nested if else ★nested if ★conditional statements ★ examples ★ if example

Tutorials